/*
     Copyright 2007 Joseph M. Ferner

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using NMock2;
using NUnit.Framework;
using OpenServers.Net.Common.FileSystem;
using OpenServers.Net.Common.Security;
using OpenServers.Net.Common.User;
using OpenServers.Net.FtpServer.State;

namespace OpenServers.Net.FtpServer.Command {
    public class MockListCommand : ListCommand {
        private readonly IList<object[]> _sendDataCalls = new List<object[]>();

        public IList<object[]> SendDataCalls {
            get { return _sendDataCalls; }
        }

        protected override void SendData(IFtpServer server, FtpState state, Stream dataStream) {
            SendDataCalls.Add(new object[] { server, state, dataStream });
        }
    }

    [TestFixture]
    public class ListCommandTest : AbstractCommandTest<MockListCommand> {

        [SetUp]
        public override void SetUp() {
            base.SetUp();
            PrivateObject.SetStaticFieldValue("system", MockSystem);
        }

        [Test]
        public void TestInvokeWithParam() {
            IDirectory dir = Mocks.NewMock<IDirectory>();
            IList<IFileSystemObject> dirItems = new List<IFileSystemObject>();
            Expect.Once.On(dir).Method("GetItems").Will(Return.Value(dirItems));
            Expect.Once.On(MockFileSystem).Method("GetDirectory").With("/").Will(Return.Value(dir));
            Expect.Once.On(dir).GetProperty("Exists").Will(Return.Value(true));
            Expect.Once.On(MockSecurityProvider).Method("CanRead").With(MockUser, dir).Will(Return.Value(true));
            Expect.Once.On(MockMessages).Method("Get150").With("/");

            PrivateObject.WrappedObject.Invoke(MockFtpServer, State, "/");

            Assert.AreEqual("/", State.CurrentDirectory);
            Assert.AreEqual(1, PrivateObject.WrappedObject.SendDataCalls.Count);
        }

        [Test]
        public void TestInvokeWithoutParam() {
            IDirectory dir = Mocks.NewMock<IDirectory>();
            IList<IFileSystemObject> dirItems = new List<IFileSystemObject>();
            Expect.Once.On(dir).Method("GetItems").Will(Return.Value(dirItems));
            Expect.Once.On(MockFileSystem).Method("GetDirectory").With("/").Will(Return.Value(dir));
            Expect.Once.On(dir).GetProperty("Exists").Will(Return.Value(true));
            Expect.Once.On(MockSecurityProvider).Method("CanRead").With(MockUser, dir).Will(Return.Value(true));
            Expect.Once.On(MockMessages).Method("Get150").With("/");

            PrivateObject.WrappedObject.Invoke(MockFtpServer, State, "");

            Assert.AreEqual("/", State.CurrentDirectory);
            Assert.AreEqual(1, PrivateObject.WrappedObject.SendDataCalls.Count);
        }

        [Test]
        public void TestInvokeBadAccess() {
            IDirectory dir = Mocks.NewMock<IDirectory>();
            Expect.Once.On(MockFileSystem).Method("GetDirectory").With("/").Will(Return.Value(dir));
            Expect.Once.On(dir).GetProperty("Exists").Will(Return.Value(true));
            Expect.Once.On(MockSecurityProvider).Method("CanRead").With(MockUser, dir).Will(Return.Value(false));
            Expect.Once.On(MockMessages).Method("Get550").With(Reason550.AccessDenied);

            PrivateObject.WrappedObject.Invoke(MockFtpServer, State, "/");

            Assert.AreEqual("/", State.CurrentDirectory);
        }

        [Test]
        public void TestInvokeDirectoryNotFound() {
            IDirectory dir = Mocks.NewMock<IDirectory>();
            Expect.Once.On(dir).GetProperty("Exists").Will(Return.Value(false));
            Expect.Once.On(MockFileSystem).Method("GetDirectory").With("/").Will(Return.Value(dir));
            Expect.Once.On(MockMessages).Method("Get550").With(Reason550.FileNotFound);

            PrivateObject.WrappedObject.Invoke(MockFtpServer, State, "/");

            Assert.AreEqual("/", State.CurrentDirectory);
        }

        [Test]
        public void TestInvokeNotLoggedIn() {
            State.User = null;
            Expect.Once.On(MockMessages).Method("Get530");
            PrivateObject.WrappedObject.Invoke(MockFtpServer, State, "/");
        }

        [Test]
        public void TestFormatAsUnixDateSameYear() {
            DateTime date = new DateTime(1977, 5, 6, 7, 8, 9);
            string result = (string)PrivateObject.ExecuteMethod("FormatAsUnixDate", date);
            Assert.AreEqual("May  6 07:08", result);
        }

        [Test]
        public void TestFormatAsUnixDateDifferentYear() {
            DateTime date = new DateTime(1978, 5, 6, 7, 8, 9);
            string result = (string)PrivateObject.ExecuteMethod("FormatAsUnixDate", date);
            Assert.AreEqual("May  6  1978", result);
        }

        [Test]
        public void TestFormatAsUnixFile() {
            DateTime lastModified = new DateTime(1977, 10, 30, 1, 2, 3);

            IFile file = Mocks.NewMock<IFile>();
            Expect.AtLeastOnce.On(file).GetProperty("Size").Will(Return.Value(100L));
            Expect.AtLeastOnce.On(file).GetProperty("LastModified").Will(Return.Value(lastModified));
            Expect.AtLeastOnce.On(file).GetProperty("Name").Will(Return.Value("test.txt"));

            Expect.AtLeastOnce.On(MockSecurityProvider).Method("CanRead").With(MockUser, file).Will(Return.Value(true));
            Expect.AtLeastOnce.On(MockSecurityProvider).Method("CanWrite").With(MockUser, file).Will(Return.Value(true));

            IList<IFileSystemObject> children = new List<IFileSystemObject>();
            children.Add(file);
            StringBuilder fileListString = new StringBuilder();
            PrivateObject.ExecuteMethod(
                "FormatAsUnix",
                new Type[] { typeof(ISecurityProvider), typeof(IUser), typeof(IEnumerable<IFileSystemObject>), typeof(StringBuilder) },
                new object[] { MockSecurityProvider, MockUser, children, fileListString });
            Assert.AreEqual("-rw-rw-rw-    1     none     none        100 Oct 30 01:02 test.txt\r\n", fileListString.ToString());
        }

        public void TestFormatAsUnixMultipleFiles() {
            DateTime lastModified = new DateTime(1977, 10, 30, 1, 2, 3);

            IList<IDirectory> childDirectories = new List<IDirectory>();
            IDirectory mockDirectory = Mocks.NewMock<IDirectory>();
            childDirectories.Add(mockDirectory);

            IFile mockFile = Mocks.NewMock<IFile>();
            Expect.AtLeastOnce.On(mockFile).GetProperty("Size").Will(Return.Value(100L));
            Expect.AtLeastOnce.On(mockFile).GetProperty("LastModified").Will(Return.Value(lastModified));
            Expect.AtLeastOnce.On(mockFile).GetProperty("Name").Will(Return.Value("test.txt"));

            IDirectory directory = Mocks.NewMock<IDirectory>();
            Expect.AtLeastOnce.On(directory).GetProperty("LastModified").Will(Return.Value(lastModified));
            Expect.AtLeastOnce.On(directory).GetProperty("Name").Will(Return.Value("test"));
            Expect.AtLeastOnce.On(directory).Method("GetDirectories").Will(Return.Value(childDirectories));

            Expect.AtLeastOnce.On(MockSecurityProvider).Method("CanRead").With(MockUser, mockFile).Will(Return.Value(true));
            Expect.AtLeastOnce.On(MockSecurityProvider).Method("CanWrite").With(MockUser, mockFile).Will(Return.Value(true));

            Expect.AtLeastOnce.On(MockSecurityProvider).Method("CanRead").With(MockUser, directory).Will(Return.Value(true));
            Expect.AtLeastOnce.On(MockSecurityProvider).Method("CanWrite").With(MockUser, directory).Will(Return.Value(true));

            IList<IFileSystemObject> children = new List<IFileSystemObject>();
            children.Add(directory);
            children.Add(mockFile);
            StringBuilder fileListString = new StringBuilder();
            PrivateObject.ExecuteMethod(
                "FormatAsUnix",
                new Type[] { typeof(ISecurityProvider), typeof(IUser), typeof(IEnumerable<IFileSystemObject>), typeof(StringBuilder) },
                new object[] { MockSecurityProvider, MockUser, children, fileListString });
            Assert.AreEqual(
                "drw-rw-rw-    1     none     none          0 Oct 30 01:02 test\r\n" +
                "-rw-rw-rw-    1     none     none        100 Oct 30 01:02 test.txt\r\n", fileListString.ToString());
        }
    }
}
